package org.ala.tiktools.rpc.kcp.netty.server.config;

import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import org.ala.tiktools.rpc.kcp.config.RpcKcpConfigInfo;
import org.ala.tiktools.rpc.kcp.netty.IKcpServerChannelConfig;
import org.ala.tiktools.rpc.kcp.netty.server.KcpServerChannel;

import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.StandardSocketOptions;
import java.util.Map;
import java.util.Objects;

import static io.netty.channel.ChannelOption.*;
import static io.netty.channel.ChannelOption.IP_TOS;

/**
 *
 * @author ala
 * @date 2025-04-14 13:20
 */
public class DefaultKcpServerChannelConfig extends DefaultChannelConfig implements IKcpServerChannelConfig {


    private final DatagramSocket javaSocket;

    public DefaultKcpServerChannelConfig(KcpServerChannel channel, DatagramSocket javaSocket) {
        super(channel, new FixedRecvByteBufAllocator(RpcKcpConfigInfo.INSTANCE.getUdpRecvBufferAllocateSize()));
        this.javaSocket = Objects.requireNonNull(javaSocket, "javaSocket");
    }


    @Override
    public Map<ChannelOption<?>, Object> getOptions() {
        return getOptions(
                super.getOptions(),
                SO_RCVBUF, SO_SNDBUF, SO_REUSEADDR, IP_TOS);
    }

    @Override
    @SuppressWarnings({"unchecked"})
    public <T> T getOption(ChannelOption<T> option) {
        if (option == SO_RCVBUF) {
            return (T) Integer.valueOf(getUdpReceiveBufferSize());
        }
        if (option == SO_SNDBUF) {
            return (T) Integer.valueOf(getUdpSendBufferSize());
        }
        if (option == SO_REUSEADDR) {
            return (T) Boolean.valueOf(isReuseAddress());
        }
        if (option == IP_TOS) {
            return (T) Integer.valueOf(getUdpTrafficClass());
        }
        return super.getOption(option);
    }

    @Override
    public <T> boolean setOption(ChannelOption<T> option, T value) {
        validate(option, value);

        if (option == SO_RCVBUF) {
            setUdpReceiveBufferSize((Integer) value);
        } else if (option == SO_SNDBUF) {
            setUdpSendBufferSize((Integer) value);
        } else if (option == SO_REUSEADDR) {
            setReuseAddress((Boolean) value);
        } else if (option == IP_TOS) {
            setUdpTrafficClass((Integer) value);
        } else {
            return super.setOption(option, value);
        }
        return true;
    }


    /**
     * udp receiver buffer size
     */
    public int getUdpReceiveBufferSize() {
        try {
            return javaSocket.getReceiveBufferSize();
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    }
    public IKcpServerChannelConfig setUdpReceiveBufferSize(int receiveBufferSize) {
        try {
            javaSocket.setReceiveBufferSize(receiveBufferSize);
            return this;
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    }
    /**
     * udp sender buffer size
     */
    public int getUdpSendBufferSize() {
        try {
            return javaSocket.getSendBufferSize();
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    }
    public IKcpServerChannelConfig setUdpSendBufferSize(int sendBufferSize) {
        try {
            javaSocket.setSendBufferSize(sendBufferSize);
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
        return this;
    }
    /**
     * Gets the {@link StandardSocketOptions#IP_TOS} option.
     */
    public int getUdpTrafficClass() {
        try {
            return javaSocket.getTrafficClass();
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    }
    public IKcpServerChannelConfig setUdpTrafficClass(int trafficClass) {
        try {
            javaSocket.setTrafficClass(trafficClass);
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
        return this;
    }
    /**
     * 单机是否可重用端口号
     */
    public boolean isReuseAddress() {
        try {
            return javaSocket.getReuseAddress();
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    }
    public IKcpServerChannelConfig setReuseAddress(boolean reuseAddress) {
        try {
            javaSocket.setReuseAddress(reuseAddress);
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
        return this;
    }

    @Override
    @Deprecated
    public IKcpServerChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) {
        super.setMaxMessagesPerRead(maxMessagesPerRead);
        return this;
    }
    /**
     *  写操作最大重试次数
     */
    @Override
    public IKcpServerChannelConfig setWriteSpinCount(int writeSpinCount) {
        super.setWriteSpinCount(writeSpinCount);
        return this;
    }
    /**
     *  链接超时毫秒数
     */
    @Override
    public IKcpServerChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) {
        super.setConnectTimeoutMillis(connectTimeoutMillis);
        return this;
    }
    /**
     *  ByteBuf内存分配器
     */
    @Override
    public IKcpServerChannelConfig setAllocator(ByteBufAllocator allocator) {
        super.setAllocator(allocator);
        return this;
    }
    /**
     *  接受消息时候ByteBuf内存分配器
     */
    @Override
    public IKcpServerChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) {
        super.setRecvByteBufAllocator(allocator);
        return this;
    }
    /**
     *  自动读取数据（是否自动触发read事件）
     */
    @Override
    public IKcpServerChannelConfig setAutoRead(boolean autoRead) {
        super.setAutoRead(autoRead);
        return this;
    }
    /**
     *  写入失败时自动关闭channel
     */
    @Override
    public IKcpServerChannelConfig setAutoClose(boolean autoClose) {
        super.setAutoClose(autoClose);
        return this;
    }
    /**
     *  消息大小估算器
     */
    @Override
    public IKcpServerChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) {
        super.setMessageSizeEstimator(estimator);
        return this;
    }
    /**
     *  写缓冲区高低水位
     *  <p> 超过high，写操作停止
     *  <p> 低于low，写操作继续
     */
    @Override
    public IKcpServerChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark) {
        super.setWriteBufferWaterMark(writeBufferWaterMark);
        return this;
    }

}
